# order_controller.py
from flask import request, jsonify, Blueprint
from datetime import datetime
from app.enums import ErrorCode
from app.service import orderService
from app.util.jwtUtil import get_user_id_from_token

order_bp = Blueprint('order', __name__)


@order_bp.route('/orders', methods=['POST'])
def create_order():
    token = request.headers.get('Authorization')
    tenant_id = get_user_id_from_token(token)
    if not tenant_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    data = request.get_json()
    required_fields = ['house_id', 'landlord_id', 'start_date', 'end_date',
                       'total_amount', 'deposit']
    if not all(field in data for field in required_fields):
        return jsonify({'code': ErrorCode.PARAM_MISSING.code,
                        'msg': '缺少必要参数'}), 400

    try:
        start_date = datetime.strptime(data['start_date'], '%Y-%m-%d').date()
        end_date = datetime.strptime(data['end_date'], '%Y-%m-%d').date()
    except ValueError:
        return jsonify({'code': ErrorCode.PARAM_INVALID.code,
                        'msg': '日期格式错误，应为YYYY-MM-DD'}), 400

    order = orderService.create_order(
        tenant_id=tenant_id,
        house_id=data['house_id'],
        landlord_id=data['landlord_id'],
        start_date=start_date,
        end_date=end_date,
        total_amount=data['total_amount'],
        deposit=data['deposit']
    )

    if order:
        return jsonify({
            'code': ErrorCode.SUCCESS.code,
            'msg': '订单创建成功',
            'data': {
                'order_id': order.order_id,
                'order_no': order.order_no,
                'status': order.status
            }
        }), 201
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '订单创建失败'}), 500


@order_bp.route('/orders/<int:order_id>', methods=['GET'])
def get_order(order_id):
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    # 调试：打印 Token 和解析的 user_id
    print(f"[DEBUG] Token: {token}")
    print(f"[DEBUG] Extracted user_id: {user_id}")

    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401


    order = orderService.get_order_by_id(order_id)
    if not order:
        return jsonify({'code': ErrorCode.ORDER_NOT_FOUND.code,
                        'msg': '订单不存在'}), 404

    # 检查用户是否有权限查看此订单(租客或房东)
    print(f"[DEBUG] Extracted order.tenant_id: {order.tenant_id}")
    print(f"[DEBUG] Extracted order.landlord_id: {order.landlord_id}")

    user_id=int(user_id)
    if user_id not in [order.tenant_id, order.landlord_id]:
        return jsonify({'code': ErrorCode.PERMISSION_DENIED.code,
                        'msg': '无权查看此订单'}), 403

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取订单成功',
        'data': {
            'order_id': order.order_id,
            'order_no': order.order_no,
            'tenant_id': order.tenant_id,
            'house_id': order.house_id,
            'landlord_id': order.landlord_id,
            'start_date': order.start_date.strftime('%Y-%m-%d'),
            'end_date': order.end_date.strftime('%Y-%m-%d'),
            'total_amount': order.total_amount,
            'deposit': order.deposit,
            'status': order.status,
            'cancel_reason': order.cancel_reason,
            'cancel_by': order.cancel_by,
            'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S') if order.created_at else None
        }
    })


@order_bp.route('/orders/tenant', methods=['GET'])
def get_tenant_orders():
    token = request.headers.get('Authorization')
    tenant_id = get_user_id_from_token(token)
    if not tenant_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    orders = orderService.get_orders_by_tenant(tenant_id)
    orders_data = [{
        'order_id': order.order_id,
        'order_no': order.order_no,
        'house_id': order.house_id,
        'landlord_id': order.landlord_id,
        'start_date': order.start_date.strftime('%Y-%m-%d'),
        'end_date': order.end_date.strftime('%Y-%m-%d'),
        'total_amount': order.total_amount,
        'status': order.status,
        'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S') if order.created_at else None
    } for order in orders]

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取租客订单列表成功',
        'data': orders_data
    })


@order_bp.route('/orders/landlord', methods=['GET'])
def get_landlord_orders():
    token = request.headers.get('Authorization')
    landlord_id = get_user_id_from_token(token)
    if not landlord_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    orders = orderService.get_orders_by_landlord(landlord_id)
    orders_data = [{
        'order_id': order.order_id,
        'order_no': order.order_no,
        'tenant_id': order.tenant_id,
        'house_id': order.house_id,
        'start_date': order.start_date.strftime('%Y-%m-%d'),
        'end_date': order.end_date.strftime('%Y-%m-%d'),
        'total_amount': order.total_amount,
        'status': order.status,
        'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S') if order.created_at else None
    } for order in orders]

    return jsonify({
        'code': ErrorCode.SUCCESS.code,
        'msg': '获取房东订单列表成功',
        'data': orders_data
    })


@order_bp.route('/orders/<int:order_id>', methods=['PUT'])
def update_order(order_id):
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)

    print(f"[DEBUG] 更新的Token: {token}")
    print(f"[DEBUG] Extracted 更新的user_id: {user_id}")
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    data = request.get_json()

    order = orderService.get_order_by_id(order_id)
    if not order:
        return jsonify({'code': ErrorCode.ORDER_NOT_FOUND.code,
                        'msg': '订单不存在'}), 404

    # 检查用户是否有权限修改此订单(租客或房东)
    user_id=int(user_id)
    order.tenant_id=int(order.tenant_id)
    order.landlord_id=int(order.landlord_id)
    if user_id not in [order.tenant_id, order.landlord_id]:
        return jsonify({'code': ErrorCode.PERMISSION_DENIED.code,
                        'msg': '无权修改此订单'}), 403

    print(f"[DEBUG] Extracted 更新的order.tenant_id: {order.tenant_id}")
    print(f"[DEBUG] Extracted 更新的order.landlord_id: {order.landlord_id}")

    # 租客只能取消订单，房东可以确认或取消订单
    allowed_updates = {}
    if user_id == order.tenant_id:
        if 'status' in data and data['status'] == 'canceled':
            allowed_updates['status'] = 'canceled'
            allowed_updates['cancel_by'] = 'tenant'
            if 'cancel_reason' in data:
                allowed_updates['cancel_reason'] = data['cancel_reason']
    elif user_id == order.landlord_id:
        if 'status' in data and data['status'] in ['confirmed', 'canceled']:
            allowed_updates['status'] = data['status']
            allowed_updates['cancel_by'] = 'landlord' if data['status'] == 'canceled' else None
            if data['status'] == 'canceled' and 'cancel_reason' in data:
                allowed_updates['cancel_reason'] = data['cancel_reason']

    if not allowed_updates:
        return jsonify({'code': ErrorCode.PERMISSION_DENIED.code,
                        'msg': '无权执行此操作'}), 403

    success = orderService.update_order(order_id, **allowed_updates)
    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code,
                        'msg': '订单更新成功'})
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '订单更新失败'}), 500


@order_bp.route('/orders/<int:order_id>', methods=['DELETE'])
def delete_order(order_id):
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code,
                        'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    order = orderService.get_order_by_id(order_id)
    if not order:
        return jsonify({'code': ErrorCode.ORDER_NOT_FOUND.code,
                        'msg': '订单不存在'}), 404

    # 只有待处理的订单可以被删除
    if order.status != 'pending':
        return jsonify({'code': ErrorCode.ORDER_STATUS_INVALID.code,
                        'msg': '只有待处理状态的订单可以删除'}), 400

    # 只有租客或房东可以删除自己的订单
    if user_id not in [order.tenant_id, order.landlord_id]:
        return jsonify({'code': ErrorCode.PERMISSION_DENIED.code,
                        'msg': '无权删除此订单'}), 403

    success = orderService.delete_order(order_id)
    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code,
                        'msg': '订单删除成功'})
    else:
        return jsonify({'code': ErrorCode.SERVER_ERROR.code,
                        'msg': '订单删除失败'}), 500